<template>
  <el-row class="tac" :style="{ height: backgroundHeight + 'px'}">
    <el-col :span="24" class="scrollable-menu">
      <h2 class="mb-2">希望信工提供的服务</h2>
      <el-menu
          default-active="2"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
      >
        <el-sub-menu index="1">
          <template #title>
            <el-icon>
              <location/>
            </el-icon>
            <span>报备管理</span>
          </template>
          <el-menu-item-group title="报备类型">
            <el-menu-item
                v-for="(item, key) in reportInfo"
                :key="key"
                :index="'1-' + key"
                @click="onMenuItemClick(key)"
            >
              {{ item.model_name }}
            </el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group title="报备统计">
            <el-menu-item index="1-2-3" @click="onMenuItemGetScoreClick()">评分查询</el-menu-item>
          </el-menu-item-group>
          <el-sub-menu index="1-4">
            <template #title>其它功能</template>
            <el-menu-item index="1-4-1">暂时没有想到</el-menu-item>
          </el-sub-menu>
        </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>
            <el-icon>
              <EditPen/>
            </el-icon>
            <span>教务管理</span>
          </template>
          <el-menu-item-group title="教务查询">
            <el-menu-item index="2-1-1">我的课表</el-menu-item>
            <el-menu-item index="2-1-2">教师课表</el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group title="教务管理">
            <el-menu-item index="2-2-3">一键排课</el-menu-item>
            <el-menu-item index="2-2-3" @click="onMenuItem_2_2_3_Click()">调课申请</el-menu-item>
            <el-menu-item index="2-2-3" @click="onMenuItem_2_2_4_Click()" >空教室查询</el-menu-item>
            <el-menu-item index="2-2-4" @click="onMenuItem_2_2_5_Click()" >我要选课</el-menu-item>
          </el-menu-item-group>
          <el-sub-menu index="2-3">
            <template #title>其它功能</template>
            <el-menu-item index="1-4-1">暂时没有想到</el-menu-item>
          </el-sub-menu>
        </el-sub-menu>
        <el-sub-menu index="3">
          <template #title>
            <el-icon>
              <Message/>
            </el-icon>
            <span>消息管理</span>
          </template>
          <el-menu-item-group title="邮件收发">
            <el-menu-item index="3-1-1">通知我的内容</el-menu-item>
            <el-menu-item index="3-1-2">我发送的内容</el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group title="未完待续">
            <el-menu-item index="3-2-1">未完待续</el-menu-item>
            <el-menu-item index="3-2-2">未完待续</el-menu-item>
          </el-menu-item-group>
        </el-sub-menu>
        <el-sub-menu v-if="shouldShowMenuItem" index="4">
          <template #title>
            <el-icon>
              <Setting/>
            </el-icon>
            <span>管理模式</span>
          </template>
          <el-sub-menu  index="4-1">
            <template #title>
              <el-icon>
                <Setting/>
              </el-icon>
              <span>审核与报备管理</span>
            </template>
            <el-menu-item-group index="4-1-1" title="报备管理" >
              <el-menu-item
                  v-for="(item, key) in reportInfo"
                  :key="key"
                  :index="'1-' + key"
                  @click="onMenuItemApproveClick(key)"
              >
                {{ item.model_name }}
              </el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group index="4-1-2" title="评分管理">
              <el-menu-item title="评分导出" @click="onMenuItemSocreFileClick()">评分导出</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
          <el-sub-menu  index="4-2">
            <template #title>
              <el-icon>
                <Setting/>
              </el-icon>
              <span>选课管理</span>
            </template>
            <el-menu-item index="4-2-1" title="选课录入" @click="onMenuItemUploadCourseClick()">选课录入
              <input
                  type="file"
                  style="display: none;"
                  ref="fileInput"
                  @change="handleFileChange"
              />
            </el-menu-item>
            <el-menu-item index="4-2-2" title="选课结果下载" @click="onMenuItemDownloadCourseResultClick()">选课结果下载</el-menu-item>
            <el-menu-item index="4-2-3" title="选课模板下载" @click="onMenuItemDownloadCourseTemplateClick()">选课模板下载</el-menu-item>
          </el-sub-menu>
          <el-sub-menu  index="4-3">
            <template #title>
              <el-icon>
                <Setting/>
              </el-icon>
              <span>课程管理</span>
            </template>
            <el-menu-item-group index="4-3-1" title="表管理" >
              <el-menu-item title="" @click="onMenuItem_4_3_2_1_Click()">调课表管理</el-menu-item>
              <el-menu-item title="" @click="onMenuItem_4_3_2_2_Click()">课程表管理</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </el-sub-menu>
        <el-menu-item index="5" @click="onMenuItem4Click()">
          <el-icon>
            <document/>
          </el-icon>
          <span>文件服务</span>
        </el-menu-item>
        <el-menu-item index="6" @click="onMenuItemfiyfishwebClick()">
          <el-icon>
            <Connection/>
          </el-icon>
          <span>可视化编程</span>
        </el-menu-item>
        <el-menu-item index="7" @click="onMenuItemAcGptClick()">
          <el-icon>
            <Connection/>
          </el-icon>
          <span>学术助手</span>
        </el-menu-item>
        <el-menu-item index="8" @click="onMenuItemAssistantClick()">
          <el-icon>
            <Connection/>
          </el-icon>
          <span>智能助理</span>
        </el-menu-item>
      </el-menu>
    </el-col>
  </el-row>
</template>

<script setup>
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting, Message, EditPen,
  Connection
}
  from '@element-plus/icons-vue'
import setting from "@/setting.js";
import {computed, getCurrentInstance, onMounted, ref} from 'vue';
import {ElMessage} from 'element-plus';
import eventBus from "@/event-bus.js";
import {jsonApi} from "@/global.js";
//高度定义
const backgroundHeight=ref(720);


//事件定义
const emit = defineEmits(['open-gpt-web','open-score-statistics-table']);

// 初始化报告信息
const reportInfo = ref([]);
// 在组件挂载后从localStorage读取数据
onMounted(() => {
  const storedReportInfo = localStorage.getItem('reportinfo');
  if (storedReportInfo) {
    reportInfo.value = JSON.parse(storedReportInfo);
  }
  backgroundHeight.value = window.innerHeight;
});
const handleOpen = (key, keyPath) => {
  console.log(key, keyPath)
}

const handleClose = (key, keyPath) => {
  console.log(key, keyPath)
}

const onMenuItemClick = async (property) => {
  eventBus.emit('report-form-table', {
    tableType: property, // 传递报备类型或其他需要的属性
  })
}
const onMenuItem_2_2_3_Click= async () => {
 eventBus.emit('course-adjustment-form-table', {
  })
}
const onMenuItem_2_2_4_Click= async () => {
  eventBus.emit('empty-classroom-query', {
  })
}
const onMenuItem_2_2_5_Click= async () => {
  eventBus.emit('course-selection-form-table', {
  })
}
const onMenuItem4Click = async () => {
  //跳转
  window.open('https://nextcloud.swjtuhc.top:1443/', '_blank');
}

//管理模式
const onMenuItemApproveClick = async (property) => {
  //跳转到管理界面 setting.APT_URL + 'admin'
  eventBus.emit('report-form-table-admin', {
    tableType: property, // 传递报备类型或其他需要的属性
  })
}

const onMenuItem_4_3_2_1_Click = async () => {
  eventBus.emit('course-adjustment-form-table-admin', {

  })
}
const onMenuItem_4_3_2_2_Click = async () => {
  eventBus.emit('course-management-admin', {
  })
}





const onMenuItemfiyfishwebClick = async () => {
  //跳转到flyfish界面 setting.APT_URL + 'admin'
  window.open('https://fiyfishweb.swjtuhc.top:1443/', '_blank');

}
//获取所有用户的当前的分数
const onMenuItemGetScoreClick = async () => {
  emit('open-score-statistics-table')
}
//获取所有用户的当前的分数
const onMenuItemSocreFileClick = async () => {
  emit('open-score-statistics-table')
}
//选课录入文件上传
const fileInput=ref(null);
const onMenuItemUploadCourseClick= async () => {
  //弹出上传文件，用data-form上传参数名excel_file
  fileInput.value.click();

}
const handleFileChange = async (event) => {
  // 现在您可以安全地使用file了
  const file = event.target.files[0];
  if (file) {
    //检查file是不是pdf或者zip
    if (file.type === 'application/xlsx') {
      // 显示上传进度
      // 在这里处理文件上传逻辑
      const formData = new FormData();
      formData.append('excel_file', file);
      try {
        const response = await fetch(setting.API_URL + 'courseselection/batchadd/', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
          },
          body: formData
        });
        const data = await response.json();
        if (response.ok) {
          ElMessage({
            message: '上传成功',
            type: 'success',
            duration: 2000
          });
        }
      } catch (error) {
        ElMessage({
          message: '上传失败',
          type: 'error',
          duration: 2000
        });
      }
    }else {
      ElMessage({
        message: '请xlsx文件',
        type: 'warning',
        duration: 2000
      });
    }
  }
};













const onMenuItemDownloadCourseResultClick= async () => {
  /*/courseselection/download/*/
  try {
    // 使用fetch API发起请求，以获取Excel文件

    const response = await jsonApi('/courseselection/download/');

    // 检查HTTP响应状态
    if (!response.ok) {
      const errorMessage = await response.text();
      throw new Error(`HTTP error: ${response.status} - ${errorMessage}`);
    }else {
      // 创建一个blob对象，它表示了一段不可变的原始数据
      const blob = await response.blob();

      // 创建一个链接元素，用于下载文件
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;

      // 设置下载的文件名，确保服务器在响应头中设置了正确的文件名
      let fileName = 'downloaded.xlsx'; // 默认文件名
      const contentDisposition = response.headers.get('content-disposition');
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="?([^"]*)"?$/);
        if (fileNameMatch) {
          fileName = fileNameMatch[1]; // 使用从响应头中提取的文件名
        }
      }

      a.download = fileName;

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      ElMessage({
        message: '下载成功',
        type: 'success',
        duration: 2000
      });
    }
  }catch (error) {
    ElMessage({
      message: '下载失败',
      type: 'error',
      duration: 2000
    });
    }
}
const onMenuItemDownloadCourseTemplateClick= async () => {
    //打开链接http://xgsys.swjtuhc.top:1080/Files/FileTemplate/选课模板.xlsx
  window.open('https://xgsys.swjtuhc.top:1443/Files/FileTemplate/选课模板.xlsx', '_blank');
}
const userGroups = localStorage.getItem('user_groups');
const shouldShowMenuItem = computed(() => {
  // 检查user_groups数组是否包含'reviews'或'DirectorOfTheTeachingAndResearchSection'
  return userGroups.includes('reviewer') || userGroups.includes('TDAdmin');
});
// ChatGPT学术版

const onMenuItemAcGptClick= async () => {
  // 获取用户输入的文本
  const url='https://acgpt.swjtuhc.top:1443/';
  emit('open-gpt-web',url);

};

//AI助手
const onMenuItemAssistantClick= async () => {
  // 获取用户输入的文本
  // 检测当前是手机还是电脑
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  if (isMobile) {
    // 手机端
    const url='https://wx.baeapps.com/api/ai_apaas/v1/wx_program/share?share_code=appULYNtvGp5cOvL09EemFG';
    emit('open-gpt-web',url);
  } else {
    // 电脑端
    const url='https://appbuilder.baidu.com/s/gfibE1aZ';
    window.open(url, '_blank');
  }

};
</script>
<style scoped>
/* 添加滚动条样式 */
.scrollable-menu {
  overflow-y: auto;
  /* 可根据需要设置最大高度，例如：
  max-height: 80vh; */
}
</style>